#include "hashtable.h"

hashtable* createTable(int size)
{
  hashtable* t = malloc(sizeof(hashtable));
  t->keyArray = malloc(sizeof(char*)*size);
  t->dataArray = malloc(sizeof(void*)*size);
  t->size = size;
  t->nbItem = 0;
  return t;
}

void freeTable(hashtable* table)
{
  assert(table != NULL && "Cannot free null pointer");
  int i;
  for(i=0;i<table->nbItem;i++)
    {
      free(table->keyArray[i]);
      free(table->dataArray[i]);
    }
  free(table->keyArray);
  free(table->dataArray);
  free(table);
  table = NULL;
}

void* getData(char* key, hashtable* table)
{
  assert(table != NULL);
  assert(key != NULL);
  int i;
  for (i=0;i<table->nbItem ;i++)
    {
      if (strcmp(key,table->keyArray[i]) == 0)
	return table->dataArray[i];
    }
  return NULL;
}

char* getKey(void* data, hashtable* table)
{
  assert(table != NULL);
  assert(data != NULL);
  int i;
  for (i=0;i<table->nbItem ;i++)
    {
      if (data == table->dataArray[i])
	return table->keyArray[i];
    }
  return NULL;
}

int existKey(char* key, hashtable* table)
{
  assert(table != NULL);
  assert(key != NULL);
  int i;
  for (i=0;i<table->nbItem;i++)
    {
      if (strcmp(key,table->keyArray[i]) == 0)
	return 1;
    }
  return 0;
}

void addData(char* key, void* data, hashtable* table)
{
  assert(table != NULL);
  assert(key != NULL);
  assert(data != NULL);
  assert(table->nbItem+1 < table->size);

  table->keyArray[table->nbItem] = strdup(key);
  table->dataArray[table->nbItem] = data;
  table->nbItem++;
}

